<?php

class UploadComponent extends Object {

    var $errors;
    var $_type;

      /**
       *
       * @param string $directory
       * @param string $real
       * @param string $thumbDir
       * @param string $file
       * @return string Uploading Image
       */
    function upload ($directory,$thumbDir,$file) {
        $this->result	= false;
        $this->logos	= false;
        $this->error		= false;

        $this->_type = array('image/jpeg','image/jpg','image/gif','image/png','image/pjpeg','image/xpng');		// Allowed type image

        if (isset($file) && is_array($file)) {

            $fileInput	= $file['name'];
            $fileTmp 	= $file['tmp_name'];
            $fileSize 		= $file['size'];
            $fileType 	= $file['type'];
            $fileError 	= $file['error'];

            ini_set('date.timezone', 'Europe/London');								// Unique time for re-naming photos for security and hashing
            $now	= time();

            $fileName = $this->_cleanName($fileInput,$now);							// Cleaning filename from extension, space and non-alphanumeric character then join with time

            if(!in_array($fileType,$this->_type)){                                              // error if not correct extension
                $this->error("7");																		//	 Only jpg,jpeg,gif and png permitted
            } else {
                if($fileError != 0){
                    switch($fileError) {
                        case 1:
                            $this->error("1");																	// File size over than maximum upload capacity on server
                            break;
                        case 2:
                            $this->error("2");																	// File size over capacity (form).
                            break;
                        case 3:
                            $this->error("3");																	// File upload just partially and not finish yet
                            break;
                        case 4:
                            $this->error("4");																	// No file uploaded
                            break;
                        case 5:
                            $this->error("5");																	// Missing temporary folder
                            break;
                        case 6:
                            $this->error("6"); 																	// Cannot write to temporary folder
                            break;
                    }
                    return false;
                    exit();
                } else {
                    if(!is_dir($directory)) {																												// create upload folder if it does not exist
                        $this->error("11");																													// upload folder not created yet
                        exit();
                    }
                    if(!is_dir($thumbDir)){
                        $this->error("11");
                        exit();
                    }

                    if (is_uploaded_file($fileTmp)) {																								  // tyring uploading image to folder
                        $output					  = $directory.$fileName.'.jpg';																// webroot/img/logos/.../filename.jpg
                        $primary				   = $directory.$fileName.'_thumb.jpg';
                        $bigThumb				= $thumbDir.$fileName.'.jpg';
                        $smallThumb				= $thumbDir.$fileName.'_thumb.jpg';
                        $tmpResolution       = getimagesize($fileTmp);
                        if($tmpResolution == false){
                            $this->error("13");                                                                                                     // Files doesn't have any resolution
                        }else{
                            if(!file_exists($output)) {
                                if (move_uploaded_file($fileTmp, $output)) {
                                    $getBigImage = exec('convert -resize 600x '.$output.' '.$primary);
                                    $bigImage		= exec('convert -resize 586x -quality 70 '.$primary.' '.$primary);
                                    $getThumb     = exec('convert -resize 300x '.$primary.' '.$bigThumb);
                                    $bigthumb 	   = exec('convert -quality 90  '.$bigThumb.' '.$bigThumb);
                                    $thumb 			 = exec('convert -quality 90 -resize 100x '.$bigThumb.' '.$smallThumb);

                                    $outputUrl	    = strstr($smallThumb,'/img/thumbs/');							// removing /app/webroot/ from url
                                    $urlFolder		 = $this->_explodeUrl($outputUrl);						// removing folder and filename ex: 2009/01/01

                                    // now mixing value on array
                                    $this->result = array('0'=>$output,'1'=>$primary,'2'=>$bigThumb,'3'=>$smallThumb,'4'=>$outputUrl);

                                    $this->logos = array(
                                        'Post'=>
                                        array('image'=>$fileName,
                                                'status'=>'0',
                                                'created'=>date("Y-m-d H:i:s", $now),
                                                'url'=>$urlFolder
                                        ));
                                } else {
                                    $this->error("8");																															// Couldn't move file to upload folder
                                    exit();
                                }
                            } else {
                                $fileName				= date("is", $now).$fileName;																							// new photos name
                                $output					  = $directory.$fileName.'.jpg';																// webroot/img/logos/.../filename.jpg
                                $primary				   = $directory.$fileName.'_thumb.jpg';
                                $bigThumb				= $thumbDir.$fileName.'.jpg';
                                $smallThumb				= $thumbDir.$fileName.'_thumb.jpg';
                                $tmpResolution       = getimagesize($fileTmp);

                                if($tmpResolution == false){
                                    $this->error("11");
                                }

                                if (move_uploaded_file($fileTmp, $output)) {
                                    $getBigImage = exec('convert -resize 600x '.$output.' '.$primary);
                                    $bigImage		= exec('convert -resize 586x -quality 70 '.$primary.' '.$primary);
                                    $getThumb     = exec('convert -resize 300x '.$primary.' '.$bigThumb);
                                    $bigthumb 	   = exec('convert -quality 90  '.$bigThumb.' '.$bigThumb);
                                    $thumb 			 = exec('convert -quality 90 -resize 100x '.$bigThumb.' '.$smallThumb);

                                    $outputUrl	    = strstr($smallThumb,'/img/thumbs/');							// removing /app/webroot/ from url
                                    $urlFolder		 = $this->_explodeUrl($outputUrl);						// removing folder and filename ex: 2009/01/01

                                    // now mixing value on array
                                    $this->result = array('0'=>$output,'1'=>$primary,'2'=>$bigThumb,'3'=>$smallThumb,'4'=>$outputUrl);

                                    $this->logos = array(
                                        'Post'=>
                                        array('image'=>$fileName,
                                                'status'=>'0',
                                                'created'=>date("Y-m-d H:i:s", $now),
                                                'url'=>$urlFolder
                                        ));
                                } else {
                                    $this->error("8");																															// Couldn't move file to upload folder
                                    exit();
                                }
                            }
                        }
                        if($thumb) {
                            $this->error("9");																																// Failed when generating thumbnails
                        }
                    }	else {
                        $this->error("10");																																	// Possible file upload attack
                    }
                }
            }
        } else {
            $this->error("4");																																				// No File uploaded
        }
    }

    /**
     * Adding message in error array
     */
    function error ($message) {
        if (!is_array($this->errors)) $this->errors = array();
        array_push($this->errors, $message);
    }

    /**
     * Explode Url
     */
    function _explodeUrl($url){
        $dataUrl = explode("/",$url);
        $newUrl	 = $dataUrl['3'].'/'.$dataUrl['4'].'/'.$dataUrl['5'].'/';

        return $newUrl;
    }

    /**
     * Explode Url
     */
    function _getFilename($url){
        $dataUrl = explode("/",$url);
        $newUrl	 = $dataUrl['6'];

        return $newUrl;
    }

     /**
      * Cleaning file image , removing space and non-alphanumeric characters
      */
    function _cleanName($fileInput,$now){
        $fileLower = strtolower($fileInput);
        $fileCleanSpace = str_replace(" ","_",$fileLower);
        $type = array(".jpg", ".jpeg", ".gif", ".png");
        $file = str_replace($type, "", $fileCleanSpace);
        $time = date("His",$now);
        App::import('Sanitize');
        $output = Sanitize::paranoid($file);
        $newOutput = $output.$time;

        return $newOutput;
    }

    /**
     * Explode File Url
     */
    function _explodeFileUrl($url){
        $dataUrl = explode("/",$url);
        $newUrl	 = $dataUrl['3'].'/'.$dataUrl['4'].'/';

        return $newUrl;
    }

}

?>
